package com.ruoyi.tuanzhang.utils;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class UnzipUtils {

    // 解压压缩包
    public static void unzip(String zipFilePath, String destDir) throws IOException {
        FileInputStream fis = new FileInputStream(zipFilePath);
        ZipInputStream zis = new ZipInputStream(fis);
        ZipEntry ze = zis.getNextEntry();

        while (ze != null) {
            File mkdirs = new File(destDir);
            if (!mkdirs.exists()) {
                mkdirs.mkdirs();    // 创建目录
            }
            String filePath = destDir + File.separator + ze.getName();
            if (!ze.isDirectory()) {
                extractFile(zis, filePath);
            } else {
                File dirToCreate = new File(filePath);
                dirToCreate.mkdir();
            }
            zis.closeEntry();
            ze = zis.getNextEntry();

        }

        zis.closeEntry();
        zis.close();
        fis.close();
    }

    /**读取文件*/
    private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
        byte[] bytesIn = new byte[4096];
        int read;
        while ((read = zipIn.read(bytesIn)) != -1) {
            bos.write(bytesIn, 0, read);
        }
        bos.close();
    }
}
